package org.test.client.ui.util.run;

import java.awt.Container;
import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JScrollPane;

import org.test.debug.Debug;

public class ExpandCompRun implements Runnable {
	
    private int ANIMATION_FRAMES=20;
    private int ANIMATION_INTERVAL=20;
    
    private int frameIndex = 0;
    
	private JComponent comp = null;
	//是否执行展开操作
	private boolean expandFlag = true;
	private int changeHeight = 0;
	private int backChangeH = 0;
	private Container parent = null;
	private boolean useDoLayout = true;
	private RunCallBack callback = null;
	
	public ExpandCompRun (JComponent comp,boolean isExpand ,int h){
		this(comp,isExpand,h,null) ;
//		this.comp = comp;
//		expandFlag = isExpand;
//		changeHeight = h;
//		backChangeH = h;
//		parent = comp.getParent();
	}
	
	public ExpandCompRun (JComponent comp,boolean isExpand ,int h,RunCallBack callback){
		this.comp = comp;
		expandFlag = isExpand;
		changeHeight = h;
		backChangeH = h;
		parent = comp.getParent();
		this.callback = callback;
		if(parent.getLayout() == null){
			useDoLayout = false;
		}
	}
	
	public void run() {
		synchronized (comp) {
			try {
				int avg = changeHeight / ANIMATION_FRAMES;
				if (avg == 0) {
					avg = 1;
				}
				for (; frameIndex < ANIMATION_FRAMES; frameIndex++) {
					// if (comp.getParent().getLayout() != null) {
					// }
					calcAndSet(avg);
					Thread.sleep(ANIMATION_INTERVAL);
				}

				if (changeHeight != 0) {
					calcAndSet(changeHeight);
				}
				if (callback != null) {
					callback.doAfterRun(comp);
				}

				Container parent2 = parent.getParent().getParent();
				if (parent2 instanceof JScrollPane) {
					Dimension d = parent.getSize();
					if (expandFlag) {
						parent.setPreferredSize(new Dimension(d.width, d.height
								+ backChangeH));
					} else {
						parent.setPreferredSize(new Dimension(d.width, d.height
								- backChangeH));
					}
					((JScrollPane) parent2).updateUI();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void calcAndSet(int a){
		if(parent.getLayout() != null){
			Dimension d = comp.getPreferredSize();
//			Debug.debug(d+"------------------expanded run ");
			if(expandFlag){
				comp.setPreferredSize(new Dimension(d.width,d.height+a));
			}else{
				comp.setPreferredSize(new Dimension(d.width,d.height-a));
			}
		}else{
			Dimension d = comp.getSize();
//			Debug.debug(d+"------------------expanded run ");
			if(expandFlag){
				comp.setSize(d.width,d.height+a);
			}else{
				comp.setSize(d.width,d.height-a);
			}
			comp.repaint();
		}
		changeHeight = changeHeight -a;
		if(useDoLayout){
			parent.doLayout();
		}
		parent.repaint();
	}


	public void setFRAMES(int aNIMATION_FRAMES) {
		ANIMATION_FRAMES = aNIMATION_FRAMES;
	}

	public void setINTERVAL(int aNIMATION_INTERVAL) {
		ANIMATION_INTERVAL = aNIMATION_INTERVAL;
	}


	public void setUseDoLayout(boolean useDoLayout) {
		this.useDoLayout = useDoLayout;
	}
	
}
